package com.company.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.bookstore.common.formatUtils.FormatUtils;
import com.company.bookstore.entities.book_module.Book;
import com.company.bookstore.entities.order_module.Order;
import com.company.bookstore.mapper.book_module.BookMapper;
import com.company.bookstore.mapper.order_module.OrderMapper;
import com.company.bookstore.qo.order_module.OrderQo;
import com.company.bookstore.service.book_module.BookService;
import com.company.bookstore.service.order_module.LogisticsService;
import com.company.bookstore.service.order_module.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 赵云霞
 * @since 2020-09-08
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    LogisticsService logisticsService;
    @Resource
    BookMapper bookMapper;
    @Resource
    BookService bookService;

    //添加订单
    @Override
    public List<Order> saveOrder(int uid, OrderQo[] orderQos) {


        List<Order> list = new ArrayList<>();

        for (int i = 0; i < orderQos.length; i++) {
            if (orderQos[i]==null){
                continue;
            }
            //转换double的值为两位小数
            double total = orderQos[i].getPrice() * orderQos[i].getNum();
            BigDecimal b = new BigDecimal(total);
            double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            Order order = Order.builder()
                    .orderNum(UUID.randomUUID().toString())//订单号随机生成
                    .status(0)//订单状态刚生成默认是下单未支付
                    .price(orderQos[i].getPrice())//订单价格，前台获取
                    .num(orderQos[i].getNum())
                    .totalPrice(df)
                    .createTime(new Date(System.currentTimeMillis()))
                    .fkUserId(uid)
                    .fkBookId(orderQos[i].getFkBookId())
                    .orderAdd(orderQos[i].getOrderAdd())//默认地址,前台传过来的默认id
                    .deleted(0)//默认未取消
                    .build();

            list.add(order);
        }
        saveBatch(list);

        return list;
    }

    @Resource
    OrderMapper orderMapper;
    //根据订单oid 查询订单详情 包括了用户，图书信息
    @Override
    public Order getOrderDetail(int oid) {

        Order order = orderMapper.getOrderDetail(oid);
        //判断status
        if(order.getStatus()==0&&isTimeOut(order.getCreateTime().getTime())){
            order.setStatus(5);
            updateById(order);
        }

        if(order.getBook()!=null){
            FormatUtils.formatOneImgUrl(order.getBook());
        }
        if(logisticsService.getLogistics(oid)!=null){
            order.setLogistics(logisticsService.getLogistics(oid));
        }
        order.setAddress(orderMapper.getOrderAddress(order.getId()));

        return order;
    }


    //查询用户下的所有订单
    @Override
    public List<Order> getOrderByUid(int uid) {
        List<Order> list = orderMapper.getOrderList(uid);
        List<Order> listArr = new ArrayList<>();

        for(int i=0;i<list.size();i++){
           if(list.get(i).getBook()!=null){
               FormatUtils.formatOneImgUrl(list.get(i).getBook());
           }
           if(list.get(i).getStatus()==0&&isTimeOut(list.get(i).getCreateTime().getTime())) {
               list.get(i).setStatus(5);
               list.get(i).setFinishTime(new Date(System.currentTimeMillis()));//超时订单增加结束时间
               listArr.add(list.get(i));
           }
        }
        updateBatchById(listArr);

        return list;
    }

    private boolean isTimeOut(long oldTime){
        long l = System.currentTimeMillis() - oldTime;
        return (int) (l / 1000 / 60 / 60) >= 1;
    }

    //删除单个订单，用于删除订单
    @Override
    public boolean delete(int uid, int oid) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>()
                .eq("fk_user_id",uid).eq("id",oid);

        return remove(queryWrapper);
    }

    //修改订单状态
    @Override
    public List<Order> updateStatus(Order[] orders) {

        List<Order> list = new ArrayList<>();
        //用于暂时存储图书对象，支付时所有库存充足才会跟新仓库和销量
        List<Book> bookList = new ArrayList<>();

        for (int i = 0; i < orders.length; i++) {
            if (orders[i] == null) {
                continue;
            }
            Integer st = orders[i].getStatus();
            if(st==4||st==3){
                orders[i].setFinishTime(new Date(System.currentTimeMillis()));
            }else if(st==2){
                logisticsService.createLogistics(orders[i].getId());//状态发货，创建物流
            }
            //前端传入状态为1，判断库存
            else{
                Order order = orderMapper.selectById(orders[i].getId());
                Book book = bookMapper.getBookById(order.getFkBookId());
                if(book.getRepositoryNum()>=order.getNum()){
                    //减库存，增加销量
                    book.setRepositoryNum(book.getRepositoryNum()-order.getNum());
                    book.setSales(book.getSales()+order.getNum());
                    //将设置好的库存和销量暂时存入列表用于更新
                    bookList.add(book);
//                    bookMapper.updateBook(book);
                }
                //只要有一次库存不足，即取消所有的更新操作
                else{
                    list=null;
                    bookList=null;
                    break;
                }
            }
            list.add(orders[i]);
        }
        //list为空，即进入判断库存方法，且库存不足，如果list不为空，则更新状态且更新库存（前提是进入了库存判断）
        if(list!=null){
            //进入库存判断，库存充足
            if(bookList!=null){
                bookService.updateBatchById(bookList);
            }
            //更新状态，会包含库存判断
            updateBatchById(list);
        }

        return list;
    }


    //修改订单数据,订单评价，订单地址，订单数量
    @Override
    public Order updateDetails(OrderQo orderQo,int oid) {


        Order order = new Order();

         if(orderQo.getId()==null){
            orderQo.setId(oid);
        }
        BeanUtils.copyProperties(orderQo,order);

        updateById(order);

        return getById(oid);
    }


    //分页查询
    @Override
    public Page<Order> getOrderPage(long current, long size) {
        //创建一个page对象
        Page<Order> pageOrder = new Page<>(current,size);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
        queryWrapper.orderByDesc("create_time");

        //条件分页查询
        return page(pageOrder,queryWrapper);

    }

    //时间范围条件查询,可分页
    @Override
    public Page<Order>  fuzzySearchOrder(OrderQo orderQo) {
        //创建一个page对象
        Page<Order> pageOrder = new Page<>(orderQo.getCurrent(), orderQo.getSize());
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
        queryWrapper.ge("create_time",orderQo.getFrom()).le("create_time",orderQo.getTo()).orderByDesc("create_time");

        return page(pageOrder,queryWrapper);

    }


//    @Override
//    public Page<Order>  fuzzySearchOrder(OrderQo orderQo) {
//        //创建一个page对象
//        Page<Order> pageOrder = new Page<>(orderQo.getCurrent(),orderQo.getSize());
//        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//
//
//        if(orderQo.getFrom() != null) {
//            String format2 = sdf.format(orderQo.getFrom());
//            if (orderQo.getFrom().equals(orderQo.getTo())) {
////                queryWrapper.like("create_time", format2);
////            }
//            else {
//                queryWrapper.ge("create_time", format2);
//            }
//        }
//        if(orderQo.getTo()!=null) {
//            String format1 = sdf.format(orderQo.getTo());
//            try{
//                Date d = new Date(sdf.parse(format1).getTime()+24*3600*1000);
//                queryWrapper.le("create_time", sdf.format(d));
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }
//        queryWrapper.orderByDesc("create_time");
//        return page(pageOrder,queryWrapper);
//    }

}